package com.ruoyi.weixin.untils;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageCompressUtils {
    
    public static MultipartFile compressImage(MultipartFile file) throws IOException {
        // 将MultipartFile对象转换为InputStream对象
        InputStream input = new ByteArrayInputStream(file.getBytes());
        
        // 压缩图片
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        int width = 550, height = 550; // 设置图片的大小, 压缩到500*500
        Thumbnails.of(input).size(width, height).toOutputStream(output);
        
        // 将输出流中的压缩后的图片转换为MultipartFile对象
        MultipartFile compressedFile = new MultipartFile() {
            @Override
            public String getName() {
                return file.getName();
            }

            @Override
            public String getOriginalFilename() {
                return file.getOriginalFilename();
            }

            @Override
            public String getContentType() {
                return file.getContentType();
            }

            @Override
            public boolean isEmpty() {
                return file.isEmpty();
            }

            @Override
            public long getSize() {
                return output.size();
            }

            @Override
            public byte[] getBytes() throws IOException {
                return output.toByteArray();
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(output.toByteArray());
            }

            @Override
            public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
                file.transferTo(dest);
            }
        };
        
        return compressedFile;
    }
}